<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" fullscreen>
    <el-card shadow="hover" header="住户信息表单">
      <el-form ref="modalForm" :model="extraDataSourece" status-icon>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item v-if="modalType === 'edit'" label="住户编号" :label-width="formLabelWidth">
              <el-input v-model="extraDataSourece.dataSource.id" disabled autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="小区名称："
              prop="dataSource.villageCode"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '名称不能为空',trigger:'blur,change'}
              ]"
            >
              <el-input :value="extraDataSourece.villageName" placeholder="请输入小区名称" autocomplete="off" @click.native="showVillageDialog" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item
              label="住户名称："
              prop="dataSource.householdName"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '名称不能为空',trigger:'blur,change'},
                { min: 3,max:10, message: '长度在3-10个字符之间',trigger:'change'}
              ]"
            >
              <el-input v-model="extraDataSourece.dataSource.householdName" placeholder="请输入用户名称" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="楼号："
              prop="dataSource.buildingCode"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '楼号不能为空',trigger:'blur,change'}
              ]"
            >
              <el-select v-model="extraDataSourece.dataSource.buildingCode" :value="extraDataSourece.dataSource.buildingCode" placeholder="请选择楼号">
                <el-option
                  v-for="item in buildingNumberList"
                  :key="item.buildingInfoId"
                  :label="item.buildingInfoNumber"
                  :value="item.buildingInfoId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="单元名称："
              prop="dataSource.unitNumber"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '单元名称不能为空',trigger:'blur,change'},
                { min: 3,max:10, message: '长度在3-10个字符之间',trigger:'change'}
              ]"
            >
              <el-input v-model="extraDataSourece.dataSource.unitNumber" placeholder="请输入单元名称 例：1单元" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="房号："
              prop="houseNumber"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '房号不能为空',trigger:'blur,change'},
                { min: 3,max:10, message: '长度在3-10个字符之间',trigger:'change'}
              ]"
            >
              <el-input v-model="extraDataSourece.houseNumber" placeholder="请输入房号 例：402" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item
              label="身份证号码："
              prop="dataSource.idCard"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '身份证号码不能为空',trigger:'blur,change'},
                { min: 18,max:18, message: '长度18个字符',trigger:'change'}
              ]"
            >
              <el-input v-model="extraDataSourece.dataSource.idCard" placeholder="请输入身份证号码" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="联系电话号码："
              prop="dataSource.contactPhone"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '联系电话号码不能为空',trigger:'blur,change'},
                { min: 6,max:11, message: '长度在6-11个字符之间',trigger:'change'}
              ]"
            >
              <el-input v-model="extraDataSourece.dataSource.contactPhone" placeholder="请输入联系电话" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item
              label="用户类型："
              prop="dataSource.householdType"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '用户类型不能为空',trigger:'blur,change'}
              ]"
            >
              <el-radio-group v-model="extraDataSourece.dataSource.householdType" :value="extraDataSourece.dataSource.householdType">
                <el-radio
                  v-for="item in householdTypeList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                >
                  {{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="用户状态："
              prop="dataSource.householdStatus"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '用户状态不能为空',trigger:'blur,change'}
              ]"
            >
              <el-radio-group v-model="extraDataSourece.dataSource.householdStatus" :value="extraDataSourece.dataSource.householdStatus">
                <el-radio
                  v-for="item in householdStatusList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                >
                  {{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item
              label="缴费状态："
              prop="dataSource.payStatus"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '缴费状态不能为空',trigger:'blur,change'}
              ]"
            >
              <el-radio-group v-model="extraDataSourece.dataSource.payStatus" :value="extraDataSourece.dataSource.payStatus">
                <el-radio
                  v-for="item in payStatusList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                >
                  {{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="缴费方式："
              prop="dataSource.payType"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '缴费方式不能为空',trigger:'blur,change'}
              ]"
            >
              <el-radio-group v-model="extraDataSourece.dataSource.payType" :value="extraDataSourece.dataSource.payType">
                <el-radio-button
                  v-for="item in payTypeList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                >
                  {{ item.value }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item
              label="可供热面积："
              prop="heatingArea"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '供热面积不能为空',trigger:'blur,change'}
              ]"
            >
              <el-input-number v-model="extraDataSourece.heatingArea" :controls="false" :precision="2" :min="0" @change="householdHeatAreaChangeHandle" />
              <span style="margin-left: 10px"> ㎡</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="建筑面积："
              prop="houseArea"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '建筑面积不能为空',trigger:'blur,change'}
              ]"
            >
              <el-input-number v-model="extraDataSourece.houseArea" :readonly="true" :controls="false" :precision="2" :min="0" />
              <span style="margin-left: 10px"> ㎡</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="往期收费状态："
              prop="dataSource.previousStatus"
              :label-width="formLabelWidth"
              :rules="[
                { required: true, message: '往期收费状态不能为空',trigger:'blur,change'}
              ]"
            >
              <el-radio-group v-model="extraDataSourece.dataSource.previousStatus" :value="extraDataSourece.dataSource.previousStatus">
                <el-radio
                  v-for="item in previousStatusList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                >
                  {{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="备注信息："
          prop="dataSource.memo"
          :label-width="formLabelWidth"
          :rules="[
            { min: 3,max:100, message: '长度在3-100个字符之间',trigger:'change,blur'}
          ]"
        >
          <el-input v-model="extraDataSourece.dataSource.memo" type="textarea" placeholder="请输入备注信息" autocomplete="off" />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover">
      <div slot="header" class="clearfix">
        <span>费用项目信息</span>
        <span style="margin-left: 20px;color: #a3a9ad;font-weight: bolder">Tips：勾选收款项进行收款</span>
      </div>
      <el-tabs type="border-card">
        <el-tab-pane label="本季应收">
          <el-table
            :key="1"
            :data="expansePayinfoDataNotPay"
            :border="true"
            align="center"
            style="width: 100%"
            empty-text="暂无数据"
            @selection-change="handleModifySelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              fixed="left"
              align="center"
            />
            <el-table-column
              label="收费项目名称"
              align="center"
              min-width="100"
              fixed="left"
              prop="expenseName"
            />
            <el-table-column
              label="价格"
              header-align="center"
              align="right"
              width="200"
              fixed="left"
            >
              <template slot-scope="{row}">
                {{ row.amountPrice }} /元
              </template>
            </el-table-column>
            <el-table-column
              label="收费方式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseTypeDictsValue(row.expenseType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="收费模式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseModelDictsValue(row.expenseModle) }}
              </template>
            </el-table-column>
            <el-table-column
              label="年 度"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ row.yearsBegin }} - {{ row.yearsEnd }}
              </template>
            </el-table-column>
            <el-table-column
              label="供热面积"
              align="center"
            >
              <template slot-scope="{row}">
                {{ row.heatArea }} ㎡
              </template>
            </el-table-column>
            <el-table-column
              label="减免金额"
              align="center"
              min-width="200"
            >
              <template slot-scope="{row}">
                <el-input-number :key="row.id" v-model="row.payReduction" :precision="2" :min="0" :max="100" :step="1" @change="reComputedPrice(row)" />
                <span style="margin-left: 10px"> 元</span>
              </template>
            </el-table-column>
            <el-table-column
              label="应收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: red;font-weight: bolder;font-size: 18px">{{ row.amountReceivable }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="实收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: #eebb39;font-weight: bolder;font-size: 18px">{{ row.paidInAmount }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="缴费状态"
              align="center"
            >
              <template slot-scope="{row}">
                <span v-if="row.payStatus === '0'" style="color: red;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
                <span v-else style="color: yellowgreen;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="本季已收">
          <el-table
            :key="2"
            :data="expansePayinfoDataHasPaid"
            :border="true"
            align="center"
            style="width: 100%"
            empty-text="暂无数据"
          >
            <el-table-column
              label="收费项目名称"
              align="center"
              min-width="100"
              fixed="left"
              prop="expenseName"
            />
            <el-table-column
              label="价格"
              header-align="center"
              align="right"
              width="200"
              fixed="left"
            >
              <template slot-scope="{row}">
                {{ row.amountPrice }} /元
              </template>
            </el-table-column>
            <el-table-column
              label="收费方式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseTypeDictsValue(row.expenseType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="收费模式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseModelDictsValue(row.expenseModle) }}
              </template>
            </el-table-column>
            <el-table-column
              label="年 度"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ row.yearsBegin }} - {{ row.yearsEnd }}
              </template>
            </el-table-column>
            <el-table-column
              label="供热面积"
              align="center"
            >
              <template slot-scope="{row}">
                {{ row.heatArea }} ㎡
              </template>
            </el-table-column>
            <el-table-column
              label="减免金额"
              align="center"
              min-width="200"
            >
              <template slot-scope="{row}">
                <el-input-number :key="row.id" v-model="row.payReduction" disabled :precision="2" :min="0" :max="100" :step="1" @change="reComputedPrice(row)" />
                <span style="margin-left: 10px"> 元</span>
              </template>
            </el-table-column>
            <el-table-column
              label="应收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: red;font-weight: bolder;font-size: 18px">{{ row.amountReceivable }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="实收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: #eebb39;font-weight: bolder;font-size: 18px">{{ row.paidInAmount }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="缴费状态"
              align="center"
            >
              <template slot-scope="{row}">
                <span v-if="row.payStatus === '0'" style="color: red;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
                <span v-else style="color: yellowgreen;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="历史收款单">
          <el-table
            :key="3"
            :data="expansePayinfoDataHistory"
            :border="true"
            align="center"
            style="width: 100%"
            empty-text="暂无数据"
          >
            <el-table-column
              label="收费项目名称"
              align="center"
              min-width="100"
              fixed="left"
              prop="expenseName"
            />
            <el-table-column
              label="价格"
              header-align="center"
              align="right"
              width="200"
              fixed="left"
            >
              <template slot-scope="{row}">
                {{ row.amountPrice }} /元
              </template>
            </el-table-column>
            <el-table-column
              label="收费方式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseTypeDictsValue(row.expenseType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="收费模式"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ getExpanseModelDictsValue(row.expenseModle) }}
              </template>
            </el-table-column>
            <el-table-column
              label="年 度"
              align="center"
              width="200"
            >
              <template slot-scope="{row}">
                {{ row.yearsBegin }} - {{ row.yearsEnd }}
              </template>
            </el-table-column>
            <el-table-column
              label="供热面积"
              align="center"
            >
              <template slot-scope="{row}">
                {{ row.heatArea }} ㎡
              </template>
            </el-table-column>
            <el-table-column
              label="减免金额"
              align="center"
              min-width="200"
            >
              <template slot-scope="{row}">
                <el-input-number :key="row.id" v-model="row.payReduction" disabled :precision="2" :min="0" :max="100" :step="1" @change="reComputedPrice(row)" />
                <span style="margin-left: 10px"> 元</span>
              </template>
            </el-table-column>
            <el-table-column
              label="应收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: red;font-weight: bolder;font-size: 18px">{{ row.amountReceivable }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="实收金额"
              align="center"
              min-width="100"
            >
              <template slot-scope="{row}">
                <span style="color: #eebb39;font-weight: bolder;font-size: 18px">{{ row.paidInAmount }}</span> /元
              </template>
            </el-table-column>
            <el-table-column
              label="缴费状态"
              align="center"
            >
              <template slot-scope="{row}">
                <span v-if="row.payStatus === '0'" style="color: red;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
                <span v-else style="color: yellowgreen;font-size: 18px;font-weight: bolder">{{ row.payStatus | getValuePayStatus(row.payStatus) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-card>
    <el-drawer
      ref="drawer"
      append-to-body
      title="收款详情"
      :visible.sync="drawer"
      direction="btt"
    >
      <el-card shadow="hover">
        <el-form align="center" size="medium" :model="confirmPayCountObj">
          <el-row :gutter="24">
            <el-col :span="12">

              <el-form-item
                label="应收总金额："
                prop="currentPayCount"
                :label-width="formLabelWidth"
                :rules="[
                  { required: true, message: '用户类型不能为空',trigger:'blur,change'}
                ]"
              >
                <el-input-number :key="confirmPayCountObj.currentPayCount" v-model="confirmPayCountObj.currentPayCount" disabled style="width: 500px;" :controls="false" :precision="2" />
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item
                label="收款方式："
                :label-width="formLabelWidth"
                :rules="[
                  { required: true, message: '收款方式不能为空',trigger:'blur,change'}
                ]"
              >
                <el-radio-group v-model="extraDataSourece.dataSource.payType" :value="extraDataSourece.dataSource.householdType">
                  <el-radio
                    v-for="item in payTypeList"
                    :key="item.code"
                    :label="item.code"
                    :value="item.code"
                  >
                    {{ item.value }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="确认收款金额："
                prop="currentPayCount"
                :label-width="formLabelWidth"
                :rules="[
                  { required: true, message: '确认收款金额不能为空',trigger:'blur,change'}
                ]"
              >
                <el-input-number :key="confirmPayCountObj.confirmCurrentPayCount" v-model="confirmPayCountObj.confirmCurrentPayCount" style="width: 500px;" :controls="false" :precision="2" />
              </el-form-item>
            </el-col>
            <el-col :span="12" />
          </el-row>
        </el-form>
      </el-card>
      <div align="center">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" :loading="drawerConfirmloading" @click.native="verifyConfirmCountHandler">{{ drawerConfirmloading ? '缴费中，请稍候 ...' : '确认收款' }}</el-button>
      </div>

    </el-drawer>
    <div slot="footer" class="dialog-footer" align="center">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="showDrawer">收 款</el-button>
    </div>
    <vallage-modal
      ref="vallageModals"
      @putSeletElementRow="getElementRowData"
    />
    <expanse-info-modal
      ref="expanseInfoModals"
      :expanse-type-array="expanseTypeList"
      :expanse-model-array="expanseModelList"
      :householde-code="currentHouseholdCode"
      @putSeletElementRow="getExPanseElementRowArrayData"
    />
    <el-dialog append-to-body title="收款单预览&打印" :visible.sync="payInfoTableVisible">
      <div id="payinfoBox" style="margin-right:10px">
        <el-form>
          <!--        表头-->
          <div style="text-align: center">
            <span style="font-size: 40px;width:100%;font-weight: bolder">北方暖暖滴供热有限公司收费单</span>
          </div>
          <!--        表格内容-->
          <el-row :gutter="24">
            <table frame="below" cellspacing="0" style="margin-left: 5px;width: 100%;font-size:20px;margin-right: 5px;margin-top: 10px">
              <tr>
                <td style="text-align: center;border: none">单据日期：{{ getNowTime() }}</td>
                <td colspan="4" style="text-align: center">缴费方式：{{ getHousehodePayTypeListDictsValue(househodeInfo.payType) }}</td>
                <td colspan="2" style="text-align: right">单据号：{{ Math.random().toString(36).toUpperCase().slice(2) }}</td>
              </tr>
            </table>
            <table cellspacing="0" style="margin-left: 5px;width: 100%;font-size:20px;margin-right: 5px;margin-top: 10px">
              <tr>
                <td style="text-align: center">户住：{{ househodeInfo.householdName }}</td>
                <td colspan="4" style="text-align: center">状态：{{ getHouseholdPayStatusListDictsValue(househodeInfo.householdStatus) }}</td>
                <td colspan="2" style="text-align: right">地址：{{ getDictsValue(househodeInfo.cotyCode,househodeInfo) }}</td>
              </tr>
            </table>
            <table border="1" cellspacing="0" style="margin-left: 5px;width: 100%;font-size:20px;margin-right: 5px">
              <thead>
                <tr>
                  <th>项目名称</th>
                  <th>供热年度</th>
                  <th>面积</th>
                  <th>单价</th>
                  <th>金额</th>
                  <th>滞纳金</th>
                  <th>总金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in hasselectedPayInfoArray">
                  <td style="text-align: center">{{ item.expenseName }}</td>
                  <td style="text-align: center">{{ item.yearsBegin }} - {{ item.yearsEnd }}</td>
                  <td style="text-align: right">{{ item.heatArea }} ㎡</td>
                  <td style="text-align: right">{{ item.amountPrice }} ￥</td>
                  <td style="text-align: right">{{ item.amountReceivable }} ￥</td>
                  <td style="text-align: right">{{ item.lateFee === null ? 0.00 : item.lateFee }} ￥</td>
                  <td style="text-align: right">{{ item.amountReceivable }} ￥</td>
                </tr>
                <tr>
                  <td style="text-align: center">收款人：{{ userinfo.username }}</td>
                  <td colspan="4" style="text-align: center">实收大写：{{ reUpcaseMoney(confirmPayCountObj.currentPayCount) }}</td>
                  <td colspan="2" style="text-align: right">实收合计：{{ confirmPayCountObj.currentPayCount }} ￥</td>
                </tr>
              </tbody>
            </table>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancelPrintPayInfo">关 闭</el-button>
        <el-button type="primary" @click="getToPrintPayInfo">打印账单</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { getAllQuarterPayInfoByHouseCode, modifyOneOrBatchPayInfo } from '@/api/ht/zffygl/zfxxgl'
const { getDictsList, getParentDictsList } = require('@/api/dicts')
const { addOnePayOrderInfo } = require('@/api/ht/zffygl/zdxxgl')
const { getDateTime } = require('@/utils/DateUtil')
const { digitUppercase } = require('@/utils/MoneyUtil')
const { modifyOneHeatingInfo } = require('@/api/ht/xqzhgl/grxxgl/grxxgl')
const { modifyOneHouseInfo } = require('@/api/ht/xqzhgl/fwgl/fwxxgl')
const { dropOneOrBatchPayInfo, processingPay } = require('@/api/ht/zffygl/zfxxgl')
const { getAllBuildingInfoByVillageCode } = require('@/api/ht/xqzhgl/lhgl/lhxxgl')
import VallageModal from '@/views/ht/xqzhgl/zhxxgl/components/villageInfomodal'
import ExpanseInfoModal from '@/views/ht/xqzhgl/zhxxgl/components/queryExpanseInfomodal'
import { addOneHouseholdInfo, modifyOneHouseholdInfo } from '@/api/ht/xqzhgl/zhgl/zhxxgl'
import { getAllExpanseInfoList } from '@/api/ht/zffygl/fyxxgl'
const { Message } = require('element-ui')
const { mapGetters } = require('vuex')
export default {
  name: 'Modal',
  components: {
    VallageModal,
    ExpanseInfoModal
  },
  filters: {
    getValuePayStatus(code) {
      if (code === '0') {
        return '未交'
      }
      return '已交'
    }
  },
  props: {
    househodeInfo: {
      type: Object,
      default: () => {
        return {
          id: '',
          householdName: '',
          householdType: '',
          unitNumber: '',
          householdAccountCode: '',
          noticeCode: '',
          houseCode: '',
          buildingCode: '',
          heatingCode: '',
          villageCode: '',
          idCard: '',
          contactPhone: '',
          householdStatus: '',
          payStatus: '',
          payType: '',
          previousStatus: '',
          memo: ''
        }
      }
    },
    householdTypeList: {
      type: Array,
      default: () => []
    },
    payStatusList: {
      type: Array,
      default: () => []
    },
    householdStatusList: {
      type: Array,
      default: () => []
    },
    payTypeList: {
      type: Array,
      default: () => []
    },
    previousStatusList: {
      type: Array,
      default: () => []
    },
    expanseTypeList: {
      type: Array,
      default: () => []
    },
    expanseModelList: {
      type: Array,
      default: () => []
    },
    payinfoStatusList: {
      type: Array,
      default: () => []
    },
    dictsInfo: {
      type: Array,
      default: () => []
    },
    alldictsInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      title: '住户&支付信息',
      drawer: false, // 是否展示支付面板
      drawerConfirmloading: false, // 支付确认加载
      showPayInfoPrinterDialogVisible: false, // 展示账单打印对话框
      payInfoTableVisible: false, // 打印预览对话框
      confirmPayCountObj: { // 确认付款实体
        currentPayCount: 0.00, // 当前应收总金额
        confirmCurrentPayCount: 0.00 // 确认收款总金额
      },
      currentHouseholdCode: '', // 当前住户编号信息
      selectType: 'addition', // 用于小区信息模块选择判断
      expanseData: [], // 费用项目信息列表
      expansePayinfoDataNotPay: [], // 费用项目支付信息列表-本季应收
      expansePayinfoDataHasPaid: [], // 费用项目支付信息列表-本季已收
      expansePayinfoDataHistory: [], // 历史收款单
      formLabelWidth: '150px', // 表单输入框字段宽度
      dialogFormVisible: false, // 对话框是否显示
      modalType: 'add',
      changflag: '0', // 供热面积是否修改标识
      extraDataSourece: {
        payee: '', // 收款人&操作人
        dataSource: {}, // 数据源
        houseNumber: '', // 房号
        houseArea: '', // 建筑面积
        heatingArea: '', // 可供热面积
        expanseIdList: [], // 选择的费用项目Id列表
        // 数据展示使用
        villageName: ''
      },
      payReductionObj: { // 减免金额
        heatingFeePayReduction: '',
        historicalArrearsPayReduction: '',
        stopWarmingPayReduction: '',
        refundInPreviousYearsPayReduction: '',
        supportExpensePayReduction: ''
      },
      amountReceivableObj: { // 应收金额
        heatingFeeAmountReceivable: '',
        historicalArrearsAmountReceivable: '',
        stopWarmingAmountReceivable: '',
        refundInPreviousYearsAmountReceivable: '',
        supportExpenseAmountReceivable: ''
      },
      paidInAmountObj: { // 实收金额
        heatingFeePaidInAmountObj: '',
        historicalArrearsPaidInAmountObj: '',
        stopWarmingPaidInAmountObj: '',
        refundInPreviousYearsPaidInAmountObj: '',
        supportExpensePaidInAmountObj: ''
      },
      buildingNumberList: [], // 对应小区楼号信息列表
      hasselectedIdArray: [], // 选择的费用项目信息
      hasselectedPayInfoArray: [] // 选择的费用项目支付信息数组对象
    }
  },
  computed: {
    ...mapGetters([
      'userinfo'
    ])
  },
  watch: {
    househodeInfo(newdata, prevdata) {
      this.currentHouseholdCode = newdata.id // 设置当前住户编号信息
      this.extraDataSourece.dataSource = newdata // 回显住户信息数据
      this.extraDataSourece.heatingArea = this.househodeInfo.heatArea // 回显可供热面积
      this.extraDataSourece.houseArea = this.househodeInfo.houseArea // 回显建筑面积
      this.extraDataSourece.houseNumber = this.househodeInfo.houseNumber // 回显住户房屋房号
      this.title = '住户信息-详情'
      this.getBuildingInfoListByVillage(this.househodeInfo.villageCode) // 获取对应小区的楼号
      this.getExpansePayInfoListHandle() // 获取对应住户的支付信息
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.value.indexOf(value) !== -1
    },
    selectedChangeHandler() {
      const dataArray = this.hasselectedPayInfoArray
      let allCount = 0.00
      dataArray.forEach(item => {
        allCount = item.amountReceivable + allCount
      })
      this.confirmPayCountObj.currentPayCount = allCount
    },
    householdHeatAreaChangeHandle() {
      this.changflag = '1'
      this.expansePayinfoData.forEach(item => {
        item.heatArea = this.extraDataSourece.heatingArea
        this.reComputedPrice(item)
      })
    },
    reUpcaseMoney(price) {
      return digitUppercase(price)
    },
    reComputedPrice(row) {
      if (row.expenseModle === '1') {
        // 按平方
        row.amountReceivable = row.heatArea * row.amountPrice - row.heatArea * row.payReduction
        if (row.amountPrice - row.payReduction < 0) {
          Message({
            message: '优惠价格不能大于费用项目价格' || 'Error',
            type: 'error',
            duration: 2 * 1000
          })
          row.payReduction = row.amountPrice // 直接固定等于原价
          row.amountReceivable = row.heatArea * row.amountPrice - row.heatArea * row.amountPrice
        }
      } else {
        row.amountReceivable = row.amountPrice - row.payReduction
        if (row.amountReceivable < 0) {
          Message({
            message: '优惠价格不能大于费用项目价格' || 'Error',
            type: 'error',
            duration: 2 * 1000
          })
          row.payReduction = row.amountPrice // 直接固定等于原价
          row.amountReceivable = 0.00
        }
      }
      // 重新计算当前选中的费用项目最终费用信息并展示到应收总金额中。 注意：把该函数放置最后
      this.selectedChangeHandler()
    },
    getExpansePayInfoListHandle() {
      this.getExpansePayInfoList()
    },
    async getExpansePayInfoList() {
      const res = await getAllQuarterPayInfoByHouseCode(this.househodeInfo.id)
      const data = res.data.main
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.expansePayinfoDataNotPay = data.NotPayQuarterPayInfoDtoList
        this.expansePayinfoDataHasPaid = data.HasPaidQuarterPayInfoDtoList
        this.expansePayinfoDataHistory = data.HistoryPaidQuarterPayInfoDtoList
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    getBuildingInfoListByVillageHandle(code) {
      this.getBuildingInfoListByVillage(code)
    },
    async getBuildingInfoListByVillage(code) {
      const res = await getAllBuildingInfoByVillageCode(code)
      const data = res.data.main
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.buildingNumberList = data
        if (this.buildingNumberList.length === 0) {
          Message({
            message: '获取成功，但当前小区没有楼号信息' || 'Error',
            type: 'info',
            duration: 2 * 1000
          })
        }
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    getNowTime() {
      return getDateTime('')
    },
    getDictsValue(code, row) {
      const parentStr = getParentDictsList(this.dictsInfo, code)
      const kidStr = getDictsList(this.alldictsInfo, code)
      const resultStr = parentStr + ' - ' + kidStr + ' - ' + row.villageName + ' - ' + row.buildingNumber + ' - ' + row.houseNumber
      return resultStr
    },
    getHouseholdPayStatusListDictsValue(code) {
      return getDictsList(this.householdStatusList, code)
    },
    getHousehodePayTypeListDictsValue(code) {
      return getDictsList(this.payTypeList, code)
    },
    getPayInfoStatusDictsValue(code) {
      return getDictsList(this.payinfoStatusList, code)
    },
    getExpanseTypeDictsValue(code) {
      return getDictsList(this.expanseTypeList, code)
    },
    getExpanseModelDictsValue(code) {
      return getDictsList(this.expanseModelList, code)
    },
    checkModelType(type) {
      this.getAllExpanseInfoListHandle() // 获取费用项目信息列表
      this.modalType = type
      // 展示对话框
      this.dialogFormVisible = true
      // 判断是编辑还是新增
      if (type === 'add') {
        this.title = '住户信息-新增'
        // 置空
        this.extraDataSourece.dataSource = {}
        this.extraDataSourece.houseNumber = ''
        this.extraDataSourece.houseArea = ''
        this.extraDataSourece.heatingArea = ''
        this.extraDataSourece.expanseIdList = []
        this.extraDataSourece.villageName = ''
      } else if (type === 'show') {
        this.title = '住户信息-浏览'
      } else {
        // edit
        this.$set(this.extraDataSourece, 'villageName', this.househodeInfo.villageName)
      }
    },
    getAllExpanseInfoListHandle() {
      this.getAllExpanseInfoList()
    },
    async getAllExpanseInfoList() {
      const res = await getAllExpanseInfoList()
      const data = res.data.main
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.expanseData = data
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    showDrawer() {
      if (this.hasselectedPayInfoArray.length === 0) {
        Message({
          message: '请勾选至少一个费用项目进行收款！' || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return false
      }
      this.drawer = true
    },
    payConfirm() {
      if (this.drawerConfirmloading) {
        return
      }
      this.$confirm('确定收款？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        this.drawerConfirmloading = true
        setTimeout(() => {
          // 模拟支付需要一定的时间
          setTimeout(() => {
            // 模拟支付需要一定的时间
            this.extraDataSourece.payee = this.userinfo.username
            // 调用支付接口
            this.processPayHandler()
          }, 400)
        }, 2000)
      })
        .catch(_ => {})
    },
    payinfoPrinterHandler() {
      // 支付成功后弹出
      this.$confirm('缴费成功！是否要打印账单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(_ => {
        // 弹出打印对话框
        this.payInfoTableVisible = true
      }).catch(_ => {
        console.log('打印支付账单出错')
      })
    },
    verifyConfirmCountHandler() {
      if (this.confirmPayCountObj.confirmCurrentPayCount !== this.confirmPayCountObj.currentPayCount) {
        Message({
          message: '应收金额与确认金额不一致，请检查！' || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return false
      }
      this.payConfirm()
    },
    processPayHandler() {
      this.processPay() // 提交支付信息
    },
    async processPay() {
      this.drawerConfirmloading = false // 关闭支付加载状态
      const res = await processingPay(this.hasselectedPayInfoArray)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.drawerConfirmloading = false // 关闭支付加载状态
        this.createPayOrderInfoHandler() // 调用提交生成支付订单信息接口
        this.payinfoPrinterHandler() // 弹出是否打印账单对话框
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    createPayOrderInfoHandler() {
      this.createPayOrderInfo()
    },
    async createPayOrderInfo() {
      const payOrderInfo = {
        orderName: '费用项目收款',
        householdCode: this.househodeInfo.id,
        orderPayType: this.househodeInfo.payType,
        orderPayAmount: this.confirmPayCountObj.confirmCurrentPayCount,
        operaPerson: this.userinfo.username
      }
      const res = await addOnePayOrderInfo(payOrderInfo)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        console.log('账单生成成功！')
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    cancelPrintPayInfo() {
      this.payInfoTableVisible = false // 关闭支付加载状态
      this.drawer = false // 关闭支付确认界面
      // 刷新住户支付信息列表
      this.getExpansePayInfoListHandle()
    },
    getToPrintPayInfo() {
      var newWin = window.open('') // 新打开一个空窗口
      var toPrint = document.getElementById('payinfoBox') // 将要被打印的东西
      newWin.document.write(toPrint.outerHTML) // 将打印内容添加进新的窗口
      newWin.document.close() // 在IE浏览器中使用必须添加这一句
      newWin.focus() // 在IE浏览器中使用必须添加这一句
      setTimeout(function() {
        newWin.print() // 打印
        // 刷新住户支付信息列表
        this.getExpansePayInfoListHandle()
      }, 100)
    },
    // 关闭支付确认函数
    cancelForm() {
      this.drawerConfirmloading = false
      this.drawer = false
      clearTimeout(this.timer)
    },
    handleConfirm() {
      // 调用修改请求
      this.$refs['modalForm'].validate((valid) => {
        if (valid) {
          this.modifyHouseholdInfoHandle() // 住户信息修改
          this.modifyOneHouseInfoHandle()// 住户房屋信息修改
          this.modifyOneHeatingInfoHandle()// 住户供热信息修改
          this.modifyOneOrBatchPayInfoHandle() // 住户费用项目待支付信息修改
        } else {
          console.log('表单缺少数据或者不符合要求')
          return false
        }
      })
    },
    showAddExpanseAndPayInfoDialog() {
      // 展示费用信息查询框
      this.$refs.expanseInfoModals.showModel()
    },
    handleConfirmCoty() {
      this.dataSource.cotyCode = this.hasSelectedCotyObj.code
      this.dialogCotyVisible = false
    },
    handleDelete(index, row) {
      const rowIdArray = []
      rowIdArray.push(row.id)
      this.dropOnePayInfoHandle(rowIdArray)
    },
    dropOnePayInfoHandle(rowIdArray) {
      this.dropOnePayInfo(rowIdArray)
    },
    async dropOnePayInfo(rowIdArray) {
      const res = await dropOneOrBatchPayInfo(rowIdArray)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        this.getExpansePayInfoListHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    showVillageDialog() {
      this.$refs.vallageModals.setShowVillageDilogVisible()
    },
    getExPanseElementRowArrayData(rowArray) {
      console.log(rowArray)
    },
    getElementRowData(row) {
      // 视图set值检测并更新视图
      this.$set(this.extraDataSourece, 'villageName', row.villageName)
      // 赋用于实际传参的值
      this.extraDataSourece.dataSource.villageCode = row.id
      this.getBuildingInfoListByVillageHandle(row.id) // 获取对应小区的楼号信息列表
    },
    modifyOneHeatingInfoHandle() {
      if (this.extraDataSourece.heatingArea === '') {
        Message({
          message: '住户供热面积不能为空' || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return false
      }
      this.modifyOneHeatingInfo()
    },
    async modifyOneHeatingInfo() {
      const obj = {
        id: this.extraDataSourece.dataSource.heatingCode, // 住户供热信息编号
        heatArea: this.extraDataSourece.heatingArea // 可供热面积
      }
      const res = await modifyOneHeatingInfo(obj)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        return false
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    modifyOneHouseInfoHandle() {
      if (this.extraDataSourece.houseNumber === '' || this.extraDataSourece.houseArea === '') {
        Message({
          message: '住户房屋房号，房屋面积不能为空' || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return false
      }
      this.modifyOneHouseInfo()
    },
    async modifyOneHouseInfo() {
      const obj = {
        id: this.extraDataSourece.dataSource.houseCode, // 住户房屋编号
        houseNumber: this.extraDataSourece.houseNumber, // 房号
        houseArea: this.extraDataSourece.houseArea // 建筑面积
      }
      const res = await modifyOneHouseInfo(obj)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        return false
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    modifyOneOrBatchPayInfoHandle() {
      if (this.hasselectedPayInfoArray.length === 0) {
        Message({
          message: '提示：当前未修改任何待支付信息。' || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        // 直接结束
        return false
      }
      this.modifyOneOrBatchPayInfo()
    },
    async modifyOneOrBatchPayInfo() {
      const res = await modifyOneOrBatchPayInfo(this.hasselectedPayInfoArray)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        this.dialogFormVisible = false
        this.getExpansePayInfoListHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    addHouseholdInfoHandle() {
      this.addHouseholdInfo()
    },
    async addHouseholdInfo() {
      const res = await addOneHouseholdInfo(this.extraDataSourece)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        this.dialogFormVisible = false
        this.reflushDataHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    modifyHouseholdInfoHandle() {
      this.modifyHouseholdInfo()
    },
    async modifyHouseholdInfo() {
      const res = await modifyOneHouseholdInfo(this.extraDataSourece.dataSource)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        this.dialogFormVisible = false
        this.reflushDataHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    handleModifySelectionChange(selections) {
      const rowObjArray = []
      for (const selection of selections) {
        rowObjArray.push(selection)
      }
      this.hasselectedPayInfoArray = rowObjArray
      this.selectedChangeHandler()
    },
    handleSelectionChange(selections) {
      // 新增项目的选择函数-表格1
      const rowIdArray = []
      for (const selection of selections) {
        rowIdArray.push(selection.expanseInfoId)
        if (this.extraDataSourece.heatingArea === 0.00) {
          Message({
            message: '注意：请填写供热面积后再次选中选项进行操作' || 'Error',
            type: 'error',
            duration: 2 * 1000
          })
        }
        if (selection.expenseName === '取暖费') {
          this.amountReceivableObj.heatingFeeAmountReceivable = this.extraDataSourece.heatingArea * selection.amountPrice - this.payReductionObj.heatingFeePayReduction
        } else if (selection.expenseName === '配套费') {
          this.amountReceivableObj.supportExpenseAmountReceivable = this.extraDataSourece.heatingArea * selection.amountPrice - this.payReductionObj.stopWarmingPayReduction
        } else if (selection.expenseName === '历史欠费') {
          this.amountReceivableObj.historicalArrearsAmountReceivable = selection.amountPrice // 暂时就是本身的价格
        } else if (selection.expenseName === '停暖') {
          this.amountReceivableObj.stopWarmingAmountReceivable = this.extraDataSourece.heatingArea * selection.amountPrice - this.payReductionObj.stopWarmingPayReduction
        } else {
          this.amountReceivableObj.refundInPreviousYearsAmountReceivable = selection.amountPrice - this.payReductionObj.refundInPreviousYearsPayReduction
        }
      }
      this.hasselectedIdArray = rowIdArray
    },
    reflushDataHandle() {
      // 调用父组件获取方法刷新数据
      this.$emit('reflushDataHandle')
    }
  }
}
</script>

<style scoped>
</style>
